<?php
namespace app\houtai\controller\user\agent;
use app\houtai\controller\BaseController;
use wechat\Wechat;

class QrcodeController extends BaseController {
  /**
   *  @brief  : 将推广员的GameID转化成微信公众号下载链接, 并生成推广员专属二维码图片
   *  @return : image
   *  @details: 
   */
  public function buildAction() {

    $GameID = $this->request->param('GameID/d', 0);   // 推广员邀请码
    $KindID = $this->request->param('KindID/d', 0);   // 小游戏
    
    if ($GameID <= 0) {
      return abort(100, "推广员邀请码[{$GameID}]无效");
    }
    
    $Agent = table('AgentReg', 'rydb.websms')->where('GameID', $GameID)->find();
    if (empty($Agent)) {
      return abort(101, "推广员[{$GameID}]不存在");
    }
    
    $Channel = $Agent['Channel'];
    
    $Share   = config("share.{$Channel}");
  
    if (empty($Share)) {
      return abort(102, "推广员[{$GameID}]渠道号[{$Channel}]配置未定义");
    }

    $Conf = config("wxgzh.{$Share['gzh_key']}");
    
    if (empty($Conf)) {
      return abort(103, "无[渠道号={$Channel}]的公众号配置");
    }

    $bgimge = APP_PATH.$this->request->module().DS.'extra'.DS.'qrbg'.DS;
    
    switch ($Channel) { // 确定背景图
      case 43661: $bgimge = $bgimge.'20190812170923.jpg'; break;  //大合集
      default:    $bgimge = '';  break;
    }

    $wx = new Wechat($Conf);
    $state = [$GameID, $KindID, $Channel];  // 顺序固定
    $state = implode('a', $state);
    
    
    $longURL = url('download/index', '', true, $Conf['BindHost'])."?state={$state}";
    $mode = $this->request->param('mode/s', '', 'strtolower');
    if ($mode == 'local') {
      $url = $longURL; // 'https://w.url.cn/s/Ad3nUT8';
    } else {
      $url = $wx->getShortUrl($longURL); // 长链接转短链接
      if ($url === false) {
        trace("长链接[{$longURL}]转短链接失败!");
        trace(['errno' => $wx->errCode, 'error' => $wx->errMsg]);
        return abort(104, "长链接[{$longURL}]转短链接失败!{$wx->errMsg}");
      }
      trace("长链接[{$longURL}]转短链接[{$url}]成功!");
    }

    try {
      
      import('qrcode', EXTEND_PATH);

      $tempfile = RUNTIME_PATH.md5($url).'.jpg';
      \QRcode::png($url, $tempfile, QR_ECLEVEL_L, 8, 1);

      if (empty($bgimge)) { // 无底图
        $dm = imagecreatefrompng($tempfile); // 二维码
      } else {  // 二维码合图
        $dm = imagecreatefromjpeg($bgimge); // 底图
        $dw = imagesx($dm);
        $dh = imagesy($dm);
        $sw = 216;
        $sh = 216;
        //////// 二维码缩放至固定尺寸 //////////////////
        $sm = imagecreatetruecolor($sw, $sh);
        $tm = imagecreatefrompng($tempfile);  // 二维码
        $eax = imagecopyresampled($sm, $tm, 0, 0, 0, 0, $sw, $sh, imagesx($tm), imagesy($tm));
        imagedestroy($tm);
        ////////////////////////////////////////////////
        $textcolor = imagecolorallocate($dm, 255, 255, 255);
        $fontFile = CORE_PATH.'captcha'.DS.'ttfs'.DS.'4.ttf';
        
        switch ($Channel) { // 适配二维码位置
          case 43661: // 大合集
            $eax = imagecopyresampled($dm, $sm, $dw / 2 + 52, $dh - $sh - 102, 0, 0, $sw + 70, $sh + 70, $sw, $sh);
            $eax = imagettftext($dm, 30, 0, $dw / 2 - 254, $dh - 84, $textcolor, $fontFile, $GameID);
            break;

          default:
            break;
        }
        imagedestroy($sm);
      }

      ob_start();
      imagejpeg($dm);
      $content = ob_get_clean();
      imagedestroy($dm);
      unlink($tempfile);
      
      $resp = response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/jpeg');
      return $resp;
    } catch (\Exception $e) {
      @unlink($tempfile);
      return abort(110, $e->getMessage());
    }
  }
}
